<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%@ include file="/common/mainhead.html" %>
<script>

var frameStr = "window.frames['toRoleManager']";
//----------------------------------------------------DataGrid初始化
function dgLoadSuccess(data){
    $(".acteditbutton").linkbutton({ text: "编辑", plain: true, iconCls: "icon-edit" });
    $(".unacteditbutton").linkbutton({ text: "编辑", plain: true, iconCls: "icon-edit", disabled: true });
    $(".stopbutton").linkbutton({ text: "停用", plain: true, iconCls: "icon-no" });
    $(".restorebutton").linkbutton({ text: "恢复", plain: true, iconCls: "icon-ok" });
    $(".removebutton").linkbutton({ text: "删除", plain: true, iconCls: "icon-remove" });
}

function stopedStyle(index, row){
    if (row.isStoped) {
        return 'background-color:#fbcdcd;';
    } 
}

var lastSelectedIndex = -1;
function selectRow(index,data){
	if(lastSelectedIndex != index){
		var queryParams = $('#dg2').datagrid('options').queryParams;
		queryParams.roleId = data.id;
		$('#dg2').datagrid('options').queryParams = queryParams;
		$("#dg2").datagrid('reload');		
		lastSelectedIndex = index;
	}
}

//----------------------------------------------------状态字段格式化

function formatDelete(value,row,index){
	return '<a class="removebutton" onclick="deleteItem(\'' + row.id + '\',\'' + row.roleName + '\')"></a>';
}

function formatEdit(value,row,index){
    if (row && row.isStoped != null) {
        if (!row.isStoped) {
            return '<a class="acteditbutton" onclick="showWindow(false, \'' + row.id + '\')"></a>';
        } else {
            return '<a class="unacteditbutton" onclick="javascript:void(0)"></a>';
        }
    }
}

function formatStoped(value,row,index){
    if (row && row.isStoped != null) {
        if (!row.isStoped) {//未停用
            return '<a class="stopbutton" onclick="stopRole(\'' + row.id + '\',' + row.isStoped+ ',\'' + row.roleName + '\')"></a>';
        } else {//已停用
            return '<a class="restorebutton" onclick="stopRole(\'' + row.id + '\',' + row.isStoped + ')"></a>';
        }
    }
}

function formatMenu(value,row,index){
	return '<a href="javascript:void(0)" onclick="showMenuWin(\'' + row.id + '\')">菜单权限</a>'; 
}

function formatState(value,row,index){
    if (row && row.isStoped != null) {
        if (!row.isStoped) {//未停用
            return UNSTOPED;
        } else {//已停用
            return STOPED;
        }
    }
}

//--------------------------------------------------------------------------操作
//打开菜单权限窗口
function showMenuWin(id){
	var dialogId = 'myDialogId';
	var title = "菜单设置";
	var options ="buttons: [{text:'确定',iconCls:'icon-ok',handler:function(){"+frameStr+".editMenuTree(\'"+id+"\')}}]";
	var content = $('#dialog_menutree_content').html();
	openFrameDialog(dialogId, title, 400, 360, content, options);
  	top$('#tree_menu').tree({
 		checkbox:true,
 		lines:true,
		url:'getMenuTreeByRoleId.do?roleId='+id,
		onLoadSuccess:function(node,data){
			var t = top$(this);
			if(data){
				top$(data).each(function(index,d){  
					if(this.state == 'closed'){
					    t.tree('expandAll');
					   }					
				})
			}			
		}
	});
}

//设置权限
function editMenuTree(id){
	//保存勾选的和半勾选的节点
	var nodes =  top$('#tree_menu').tree('getChecked', ['checked', 'indeterminate']);
	var s = '';
 	top$(nodes).each(function(index, item){
		if( s != '' ) s+= normalFlag;
		s += item.id;
	})
 	$.post('saveRoleMenuForRole.do',{roleId:id,menuIds:s},function(data){
    	if(data.flag == JSON_FLAG_SUCCESS){
    		top$('#myDialogId').dialog('close');
			top$.messageBox5s(OPT_SUCCESS);
		}else{
			top$.messageBox5s(OPT_FAIL + ':' + data.errmsg);
		}    
	});
}

//停用/恢复
function stopRole(id, isStoped, roleName){
	var adminRoleName = $('#hide_admin_role').val();
	if(roleName && roleName == adminRoleName){
		top$.messageBox5s('无法停用管理员角色');
	}else{
		top$.messager.confirm('系统提示',isStoped ? "确定恢复角色吗？" : "确定停止角色吗？", function(r){
			if(r){
		        $.post("stopOneRole.do",{id:id,isStoped:isStoped},function(data){
		        	if(data.flag == JSON_FLAG_SUCCESS){
		    			$('#dg').datagrid('reload');
		    			top$.messageBox5s(OPT_SUCCESS);
		    		}else{
		    			top$.messageBox5s(OPT_FAIL + ':' + data.errmsg);
		    		}     
		        });
			}   		
		});
	}
}

//删除
function deleteItem(id, roleName){
	var adminRoleName = $('#hide_admin_role').val();
	if(roleName != adminRoleName){
		top$.messager.confirm('系统提示',"确定删除角色信息吗？", function(r){
			if(r){
	            $.post("deleteOneRole.do",{id:id},function(data){
	            	if(data.flag == JSON_FLAG_SUCCESS){
	        			$('#dg').datagrid('reload');
	        			clearDataGrid('dg2');
	        			top$.messageBox5s(DEL_SUCCESS);
	        		}else{
	        			top$.messageBox5s(DEL_FAIL + ':' + data.errmsg);
	        		}     
	            });
			}    		
		});
	}else{
		top$.messageBox5s('无法删除管理员角色');
	}
}

function showWindow(isAdd, id){
	var dialogId = 'myDialogId';
	var title = isAdd?'新增':'修改';
	var okFunc = isAdd?'addItem()':'editItem(\''+ id +'\')';
	var options ="buttons: [{text:'确定',iconCls:'icon-ok',handler:function(){"+frameStr+"."+ okFunc +"}},{text:'取消',iconCls:'icon-cancel',handler:function(){$('#"+ dialogId +"').dialog('close')}}]";
	var content = $('#dialog_content').html().replaceAll('e-validatebox','easyui-validatebox').replaceAll('e-textbox','easyui-textbox');
	openFrameDialog(dialogId, title, 420, 150, content, options);
	if (!isAdd) {
		$.ajax({
			url : 'getOneRoleById.do',
			async : false,
			type : "POST",
			dataType : "json",
			data : {id:id},
			success : function(data) {
				if (data.flag == JSON_FLAG_SUCCESS) {
					top$('#win_txt_roleName').val(data.roleName);
					top$('#win_txt_roleDesc').textbox('setValue',data.roleDesc);
					top$("#form1").form("validate");
					top$('#win_txt_roleName').attr('disabled',true);
				} else {
					top$.messageBox5s(ERROR_ITEMMISS);
					return;
				}
			}
		});
	}
}

function addItem() {
	var isValid = top$("#form1").form("validate");
	if (isValid) {
		top$.messager.progress();
		var roleName = top$('#win_txt_roleName').val();
		var roleDesc = top$('#win_txt_roleDesc').val();
		$.post('addOneRole.do', {
			roleName : roleName,
			roleDesc : roleDesc
		}, function(data) {
			top$.messager.progress('close');
			if (data.flag == JSON_FLAG_SUCCESS) {
				$('#dg').datagrid('reload');
				top$('#myDialogId').dialog('close');
				top$.messageBox5s(ADD_SUCCESS);
			} else {
				top$.messageBox5s(ADD_FAIL + ':' + data.errmsg);
			}
		});
	}
}

function editItem(id) {
	var isValid = top$("#form1").form("validate");
	if (isValid) {
		top$.messager.progress();
		var roleDesc = top$('#win_txt_roleDesc').val();
		$.post('editOneRole.do', {
			id:id,
			roleDesc:roleDesc
		}, function(data) {
			top$.messager.progress('close');
			if (data.flag == JSON_FLAG_SUCCESS) {
				$('#dg').datagrid('reload');
				top$('#myDialogId').dialog('close');
				top$.messageBox5s(EDIT_SUCCESS);
			} else {
				top$.messageBox5s(EDIT_FAIL + ':' + data.errmsg);
			}
		});
	}
}


</script>
</head>
<body>
<div id="toolbar" style="padding:3px;height:25px;">
	<span style="float:left;">
		<a href="javascript:void(0)" onclick="showWindow(true);" class="easyui-linkbutton" iconCls="icon-add" plain="true">新增</a>
	</span>
</div>            
<div id="div_main" class="easyui-layout">
<div region="west" style="width:50%" border="false">
<table id="dg" class="easyui-datagrid" title="角色管理"
	data-options="url:'getRolesInPage.do',width:'100%',height:'100%',rownumbers:true,loadMsg:'数据加载中，请稍后......',
	singleSelect:true,pagination:true,pageSize:20,pageList: [20, 50, 100],toolbar:'#toolbar',method:'get',
	onLoadSuccess:dgLoadSuccess,rowStyler:stopedStyle,onSelect:selectRow">
	<thead>
		<tr>
			<th data-options="field:'opt1',align:'center',formatter:formatDelete,width:'10%'">删除</th>
			<th data-options="field:'opt2',align:'center',formatter:formatEdit,width:'10%'">修改</th>
			<th data-options="field:'opt3',align:'center',formatter:formatStoped,width:'12%'">停用/恢复</th>
			<th data-options="field:'opt4',align:'center',formatter:formatMenu,width:'10%'">权限</th>
			<th data-options="field:'roleName',width:'15%'">角色名</th>
			<th data-options="field:'roleDesc',width:'30%'">描述</th>
			<th data-options="field:'isStoped',formatter:formatState,width:'10%'">状态</th>
		</tr>	
	</thead>
</table>
</div>
<div id="toolbar2" style="padding:3px;height:25px;"></div>
<div region="center" style="width:50%" border="false">
	<table id="dg2" class="easyui-datagrid" title="成员列表" data-options="url:'getUsersByRoleId.do',width:'100%',height:'100%',toolbar:'#toolbar2',rowStyler:stopedStyle">
	<thead>
		<tr>			
			<th data-options="field:'userName',width:'40%'">用户名</th>
			<th data-options="field:'realName',width:'40%'">姓名</th>
			<th data-options="field:'isStoped',formatter:formatState,width:'20%'">状态</th>
		</tr>	
	</thead>
	</table>
</div>
</div>

<div id="dialog_menutree_content">
	<ul id="tree_menu">
	</ul>
</div>
<div id="dialog_content">
	<form id="form1" style="margin:15px 10px;">
		<table>
			<tbody>
				<tr>
					<td style="width:60px;">角色名</td>
					<td><input data-options="required:true" class="e-validatebox textbox" style="width:120px;" id="win_txt_roleName"/></td>
					<td style="width:60px;">描述</td>
					<td><input class="e-textbox" style="width:120px;" id="win_txt_roleDesc"/></td>
				</tr>
			</tbody>
		</table>	
	</form>
</div>
<input id="hide_admin_role" type="hidden" value="${rolekey}" /> 
</body>
</html>